package com.yantong.service.impl;

import com.yantong.constant.*;
import com.yantong.exception.BDException;
import com.yantong.mapper.*;
import com.yantong.pay.yfz.pay.YFZPayutil;
import com.yantong.pojo.vo.ListWorkOrderVo;
import com.yantong.service.*;
import com.yantong.utils.CommonUtils;
import com.yantong.utils.DateUtils;
import com.yantong.utils.PageUtils;
import com.yantong.pojo.CommissionLog;
import com.yantong.pojo.CommissionLogExample;
import com.yantong.pojo.Order;
import com.yantong.pojo.OrderProduct;
import com.yantong.pojo.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * @author kanghaixin
 * @date 2018/9/3.16:38
 */

@Service
public class WorkOrderServiceImpl implements WorkOrderService {
	@Autowired
	private WorkOrderMapper workOrderMapper;
	@Autowired
	private WorkCommentMapper workCommentMapper;
	@Autowired
	private OrderProductMapper orderProductMapper;
	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private MemberMapper memberMapper;
	@Autowired
	private CommissionLogMapper commissionLogMapper;
	@Autowired
	private CarMapper carMapper;
	@Autowired
	private WorkClassService workClassService;

	@Autowired
	@Lazy
	private PayService payService;
	@Autowired
	private OrderSplitInfoMapper orderSplitInfoMapper;
	@Autowired
	private CentreService centreService;

	@Autowired
	private TicketService ticketService;

	@Autowired
	private WorkConfigMapper workConfigMapper;

	@Value("${Applet.TemplatemsgCreateUserUrl}")
	private String templatemsgCreateUserUrl;

	private static Logger logger = LoggerFactory.getLogger(WorkOrderServiceImpl.class);




	@Override
	public int update(WorkOrder workOrder) {
		if (workOrder == null || workOrder.getId() == null) {
			return 0;
		}
		return workOrderMapper.updateByPrimaryKeySelective(workOrder);
	}

	@Override
	public WorkOrder getByKey(Long workId) {
		if (workId == null) {
			return null;
		}
		return workOrderMapper.selectByPrimaryKey(workId);
	}

	@Override
	public List<WorkComment> getWorkComment(Long workId) {
		WorkCommentExample example = new WorkCommentExample();
		example.or().andWorkIdEqualTo(workId);
		example.setOrderByClause("create_time asc");
		return workCommentMapper.selectByExample(example);
	}




	@Override
	public PageUtils<WorkOrder> listFinanceWorkOrders(String queryItem, Integer status, Long centreId, Date start, Date end, int offset, int limit) {
		Map<String, Object> params = new HashMap<>(4);
		if (StringUtils.isNotEmpty(queryItem)) {
			params.put("queryItem", queryItem);
		}
		if (start != null) {
			params.put("start", start);
		}
		if (end != null) {
			params.put("end", end);
		}
		if (status != null) {
			params.put("status", status);
		}
		if (centreId != null) {
			params.put("centreId", centreId);
		}
		PageUtils<WorkOrder> pageUtils = new PageUtils<>();
		int total = workOrderMapper.countFinanceOrdersByParams(params);
		if (total > 0) {
			pageUtils.setRows(workOrderMapper.listFinanceOrdersByParams(params, new RowBounds(offset, limit)));
			pageUtils.setTotal(total);
		}
		return pageUtils;
	}

	@Override
	public List<WorkOrder> listFinanceWorkOrders(String queryItem, Integer status, Long centreId, Date start, Date end) {
		Map<String, Object> params = new HashMap<>(4);
		if (StringUtils.isNotEmpty(queryItem)) {
			params.put("queryItem", queryItem);
		}
		if (start != null) {
			params.put("start", start);
		}
		if (end != null) {
			params.put("end", end);
		}
		if (status != null) {
			params.put("status", status);
		}
		if (centreId != null) {
			params.put("centreId", centreId);
		}
		return workOrderMapper.listFinanceOrdersByParams(params);
	}

	@Override
	public int financeRefuseWork(WorkOrder workOrder) {
		if (workOrder == null) {
			return 0;
		}
		WorkOrder wo = workOrderMapper.selectByPrimaryKey(workOrder.getId());
		workOrder.setClosetime(new Date());
		workOrder.setStatus(WorkOrderStatus.closed.getCode());

		WorkComment comment = new WorkComment();
		comment.setWorkId(workOrder.getId());
		comment.setKefuId(workOrder.getKefuid());
		comment.setKefuName(workOrder.getKefuname());
		comment.setCommentStatus(WorkOrderStatus.closed.getCode());
		comment.setRemark(BusinessCode.FINANCE_REFUSE_WORKORDER.getMsg());
		workCommentMapper.insertSelective(comment);

		int total = orderProductMapper.countByOrderIdAndStatus(wo.getOid(), OrderStatus.work_access.getCode());
		if (total <= 1) {
			Order order = new Order();
			order.setId(wo.getOid());
			order.setStatus(OrderStatus.delivery_success.getCode());
			order.setFetchTime(new Date());
			orderMapper.updateByPrimaryKeySelective(order);
		}

		/**已收货订单明细**/
		OrderProduct op = new OrderProduct();
		op.setId(wo.getOgid());
		op.setStatus(OrderStatus.delivery_success.getCode());
		orderProductMapper.updateByPrimaryKeySelective(op);

		return workOrderMapper.updateByPrimaryKeySelective(workOrder);
	}






	/**
	 * 退款订单数量  分佣处理
	 *
	 * @param order
	 * @param op
	 * @param workOrder
	 */
	public void refundCommissionUpdate(Order order, OrderProduct op, WorkOrder workOrder) {
		CommissionLogExample cle = new CommissionLogExample();
		CommissionLogExample.Criteria criteria = cle.createCriteria();
		criteria.andOrderIdEqualTo(workOrder.getOid()).andOrderProductIdEqualTo(workOrder.getOgid()).andCentreIdEqualTo(workOrder.getCentreId());

		List<CommissionLog> cls = commissionLogMapper.selectByExample(cle);
		if (CollectionUtils.isNotEmpty(cls)) {
			// CommissionLog cl = cls.get(0);

			//购买总数量
			Integer total = op.getTotal();
			//退款数量
			Integer refundNum = op.getRefundNum();

			for (CommissionLog cl : cls) {
				cl.setOrderSn(order.getOrdersn());
//                BigDecimal deduct=new BigDecimal("0");
				BigDecimal commission = cl.getCommission();
				if (workOrder.getType() == 1) {
					if (op.getTotal() > workOrder.getNums()) {
						//退全款，按比例发放佣金，删除佣金记录
//                        int t = op.getTotal() - workOrder.getNums();
//                        BigDecimal deduct = cl.getCommission().multiply(BigDecimal.valueOf(t))
//                                .divide(BigDecimal.valueOf(op.getTotal()), 2, RoundingMode.HALF_UP);
						//总分佣
						BigDecimal sumCommission = cl.getCommission();
						if (sumCommission == null || sumCommission.compareTo(BigDecimal.ZERO) <= 0) {
							continue;
						}
						sumCommission = sumCommission.add(cl.getRefundCommission() == null ? BigDecimal.ZERO : cl.getRefundCommission());
						//一个 orderProduct 所得分佣
						BigDecimal eachCommission = sumCommission.divide(new BigDecimal(total.toString()), 2);
						//退款减去分佣
						BigDecimal refundCommission = eachCommission.multiply(new BigDecimal(refundNum.toString()));
						//减去退款 orderProduct数量的分佣
						BigDecimal newCommission = sumCommission.subtract(refundCommission);
						cl.setCommission(newCommission);
						cl.setRefundCommission(refundCommission);
						commissionLogMapper.updateByPrimaryKeySelective(cl);
					} else {
						//更新佣金记录为已删除
						cl.setDel(1);
						commissionLogMapper.updateByPrimaryKeySelective(cl);

					}
				}
				//如果 佣金不等于已删除.并且未发放,照成发放佣金.
//                if (cl.getIsGrant()==0){
//                    if (cl.getDel()!=1){
//                        commissionService.grant(cl,"售后发佣金扣除商户余额,".concat(op.getProductName()).concat(",销售价:").concat(op.getPrice().toString()).concat(",成本价:").concat(op.getCostprice().multiply(new BigDecimal(op.getTotal())).toString()).concat("订单号："));
//                    }
//                    //否则扣门店佣金给站长
//                }else{
//                    if( workOrder.getType() == 1 &&cl.getIsGrant()==1){
//                        cl.setCommission(commission.subtract(deduct).negate());
//                        commissionService.grant(cl,"订单售后扣除门店佣金增加商户余额,".concat(op.getProductName()).concat(",销售价:").concat(op.getPrice().toString()).concat(",成本价:").concat(op.getCostprice().multiply(new BigDecimal(op.getTotal())).toString()).concat("订单号："));
//                    }
//
//                }
			}
		}
	}

	@Override
	public PageUtils<WorkOrder> listWorkOrders(ListWorkOrderVo listWorkOrderVo, int offset, int limit) {
		if (listWorkOrderVo.getPayTimeStart() != null) {
			listWorkOrderVo.setPayTimeStart(DateUtils.getDateStartTime(listWorkOrderVo.getPayTimeStart()));
		}
		if (listWorkOrderVo.getPayTimeEnd() != null) {
			listWorkOrderVo.setPayTimeEnd(DateUtils.getDateEndTime(listWorkOrderVo.getPayTimeEnd()));
		}
		if (listWorkOrderVo.getStart() != null) {
			listWorkOrderVo.setStart(DateUtils.getDateStartTime(listWorkOrderVo.getStart()));
		}
		if (listWorkOrderVo.getEnd() != null) {
			listWorkOrderVo.setEnd(DateUtils.getDateEndTime(listWorkOrderVo.getEnd()));
		}
		PageUtils<WorkOrder> pageUtils = new PageUtils<>();
		int total = workOrderMapper.countByParams(listWorkOrderVo);
		if (total > 0) {
			pageUtils.setTotal(total);
			List<WorkOrder> list = workOrderMapper.listByParams(listWorkOrderVo, new RowBounds(offset, limit));
			for (WorkOrder wo : list) {
				if (wo.getMid() == null) {
					continue;
				}
				Car car = carMapper.getByTmid(wo.getMid());
				if (car == null) {
					continue;
				}
				wo.setCarName(car.getUsername());
			}
			pageUtils.setRows(list);
		}
		return pageUtils;
	}

	/**
	 * 售后工单总计
	 *
	 * @return
	 */
	public String sumWorkMoney(ListWorkOrderVo listWorkOrderVo) {
		if (listWorkOrderVo.getPayTimeStart() != null) {
			listWorkOrderVo.setPayTimeStart(DateUtils.getDateStartTime(listWorkOrderVo.getPayTimeStart()));
		}
		if (listWorkOrderVo.getPayTimeEnd() != null) {
			listWorkOrderVo.setPayTimeEnd(DateUtils.getDateEndTime(listWorkOrderVo.getPayTimeEnd()));
		}
		if (listWorkOrderVo.getStart() != null) {
			listWorkOrderVo.setStart(DateUtils.getDateStartTime(listWorkOrderVo.getStart()));
		}
		if (listWorkOrderVo.getEnd() != null) {
			listWorkOrderVo.setEnd(DateUtils.getDateEndTime(listWorkOrderVo.getEnd()));
		}
		return workOrderMapper.sumWorkMoney(listWorkOrderVo);
	}

	@Override
	public List<WorkOrder> listWorkOrder(ListWorkOrderVo listWorkOrderVo) {
		if (listWorkOrderVo.getPayTimeStart() != null) {
			listWorkOrderVo.setPayTimeStart(DateUtils.getDateStartTime(listWorkOrderVo.getPayTimeStart()));
		}
		if (listWorkOrderVo.getPayTimeEnd() != null) {
			listWorkOrderVo.setPayTimeEnd(DateUtils.getDateEndTime(listWorkOrderVo.getPayTimeEnd()));
		}
		if (listWorkOrderVo.getStart() != null) {
			listWorkOrderVo.setStart(DateUtils.getDateStartTime(listWorkOrderVo.getStart()));
		}
		if (listWorkOrderVo.getEnd() != null) {
			listWorkOrderVo.setEnd(DateUtils.getDateEndTime(listWorkOrderVo.getEnd()));
		}

		List<WorkOrder> list = workOrderMapper.listByParams(listWorkOrderVo);
		if (CollectionUtils.isNotEmpty(list)) {
			for (WorkOrder wo : list) {
				if (wo.getMid() != null) {
					continue;
				}
				Car car = carMapper.getByTmid(wo.getMid());
				if (car == null) {
					continue;
				}
				wo.setCarName(car.getUsername());
			}
		}
		return list;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int saveWorkComment(WorkComment workComment) {
		if (workComment == null) {
			return 0;
		}
		if (StringUtils.isEmpty(workComment.getRemark())) {
			throw new BDException("无法提交空白内容");
		}
		WorkOrder workOrder = new WorkOrder();
		workOrder.setId(workComment.getWorkId());
		workOrder.setIsreply(1);
		workOrderMapper.updateByPrimaryKeySelective(workOrder);
		return workCommentMapper.insertSelective(workComment);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int closeWork(WorkOrder workOrder) {
		if (workOrder == null) {
			return 0;
		}
		workOrder.setClosetime(new Date());
		workOrder.setStatus(WorkOrderStatus.closed.getCode());

		WorkComment comment = new WorkComment();
		comment.setWorkId(workOrder.getId());
		comment.setKefuId(workOrder.getKefuid());
		comment.setKefuName(workOrder.getKefuname());
		comment.setCommentStatus(WorkOrderStatus.closed.getCode());
		comment.setRemark(BusinessCode.CUSTOMER_CLOSE_WORKORDER.getMsg());
		workCommentMapper.insertSelective(comment);
		//获取售后工单里面的订单Id
		WorkOrder work = workOrderMapper.selectByPrimaryKey(workOrder.getId());
		int total = orderProductMapper.countByOrderIdAndStatus(work.getOid(), OrderStatus.work_access.getCode());
		if (total <= 1) {
			Order order = new Order();
			order.setId(work.getOid());
			order.setStatus(OrderStatus.delivery_success.getCode());
			order.setFetchTime(new Date());
			orderMapper.updateByPrimaryKeySelective(order);
		}

		OrderProduct op = new OrderProduct();
		op.setId(work.getOgid());
		op.setStatus(OrderStatus.delivery_success.getCode());
		orderProductMapper.updateByPrimaryKeySelective(op);

		return workOrderMapper.updateByPrimaryKeySelective(workOrder);
	}


	@Override
	public int forwardCw(WorkOrder workOrder) {
		if (workOrder == null) {
			return 0;
		}
		Long wId = workOrder.getId();
		if (wId == null) {
			return 0;
		}
		WorkOrder wo = workOrderMapper.selectByPrimaryKey(wId);
		if (wo == null) {
			logger.info("not found workOrder by id:{}", wId);
			return 0;
		}
		Long orderProductId = wo.getOgid();
		if (orderProductId == null) {
			logger.info("not found orderProductId");
			return 0;
		}
		OrderProduct op = orderProductMapper.selectByPrimaryKey(orderProductId);
		if (op == null) {
			logger.info("not found orderProduct info by id:{}", orderProductId);
			return 0;
		}

		//如果工单商品为余额支付，将前端输入的微信支付金额设置为 0 ， 余额支付退余额 微信支付退微信
		Order order = orderMapper.selectByPrimaryKey(op.getOrderid());
		BigDecimal price = BigDecimal.ZERO;
		if(ProductType.Normal.getType() == order.getOrderType()){
			price = op.getPrice();
		}else{
			price = order.getPayprice();
		}

		if (order.getPaytype() == 1) {
			//判断输入金额是否大于订单商品实际金额
			if (workOrder.getPaymoney().doubleValue() > price.doubleValue()) {
				throw new BDException(BusinessCode.WORK_ORDER_MONEY_ERROR);
			}
			//修改  余额退款金额-输入金额
			workOrder.setCredit2money(workOrder.getCredit2money());
			workOrder.setPaymoney(new BigDecimal("0"));
		}
		if (workOrder.getNums() > op.getTotal()) {
			throw new BDException(BusinessCode.WORK_ORDER_NUMS_ERROR);
		}

		workOrder.setStatus(WorkOrderStatus.financeDeal.getCode());
		workOrder.setResponse(StringUtils.isEmpty(workOrder.getResponse()) ? "供应商" : workOrder.getResponse());
		workOrder.setMoney(workOrder.getCredit2money().add(workOrder.getPaymoney()));

		if (workOrder.getMoney().doubleValue() > price.doubleValue()) {
			throw new BDException(BusinessCode.WORK_ORDER_MONEY_ERROR);
		}

		WorkClass wc = workClassService.getByKey(workOrder.getType());
		if (wc != null) {
			workOrder.setTypename(wc.getTypename());
			if (wc.getId() == 1) {
				//退全款
				workOrder.setCommissionMoney(op.getCommision1()== null?BigDecimal.ZERO:op.getCommision1().multiply(BigDecimal.valueOf(workOrder.getNums()))
						.divide(BigDecimal.valueOf(op.getTotal()), 2, RoundingMode.HALF_UP));
			}
		}

		WorkComment comment = new WorkComment();
		comment.setWorkId(workOrder.getId());
		comment.setKefuId(workOrder.getKefuid());
		comment.setKefuName(workOrder.getKefuname());
		comment.setCommentStatus(WorkOrderStatus.financeDeal.getCode());

		String remark = String.format(BusinessCode.FORWORD_CW_COMMENT.getMsg(), workOrder.getCredit2money(), workOrder.getPaymoney());
		logger.info("forwardCw comment remark:{}", remark);
		comment.setRemark(remark);
		workCommentMapper.insertSelective(comment);
		return workOrderMapper.updateByPrimaryKeySelective(workOrder);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int cwRefund(Long workId, Long aid, String aName) {
		if (workId == null) {
			return 0;
		}

		WorkOrder workOrder = workOrderMapper.selectByPrimaryKey(workId);
		if (workOrder == null) {
			return 0;
		}
		if (workOrder.getStatus() == WorkOrderStatus.over.getCode()) {
			throw new BDException(BusinessCode.WORK_ORDER_PAYED);
		}
		workOrder.setPaytime(new Date());
		Long orderId = workOrder.getOid();
		if (orderId == null) {
			return 0;
		}
		Order order = orderMapper.selectByPrimaryKey(orderId);
		if (order == null) {
			return 0;
		}

		if (workOrder.getOgid() == null) {
			return 0;
		}

		OrderProduct op = orderProductMapper.selectByPrimaryKey(workOrder.getOgid());
		if (op == null) {
			return 0;
		}
		workOrder.setStatus(RefundStatus.refunded.getCode());
		workOrder.setCaiwuid(aid);
		workOrder.setCaiwuname(aName);
		workOrder.setPaytime(new Date());
		workOrderMapper.updateByPrimaryKeySelective(workOrder);

		//门店费率记录失效操作
//        CollectionFlow collectionFlow = collectionFlowMapper.getByOrderId(workOrder.getOid().toString());
//        if(collectionFlow != null){
//            collectionFlow.setDelFlag(1); //已失效
//            collectionFlowMapper.insertSelective(collectionFlow);
//        }

		if (order.getTrId() != null) {
			//退还优惠券
			ticketService.updateRecordToNoUse(order.getTrId());
		}

		if (PayType.WX_PAY.equals(order.getPaytype()) || PayType.WX_APP_PAY.equals(order.getPaytype())) {
			String sn = DateUtils.format(new Date(), "ddHHmmss");
			String refundNo = "REFUND".concat(sn);
			try {
				List<OrderSplitInfo> list = orderSplitInfoMapper.selectByOutTradeNo(order.getOutTradeNo());
				Centre centre = centreService.getByKey(order.getCentreId());
				String notifyUrl = templatemsgCreateUserUrl + "/notify/yfz/refundNotify";// 退款结果通知
				YFZPayutil.refundApply(order.getPayprice(), order.getOutTradeNo(), centre, refundNo, notifyUrl, list.get(0).getSplitResultInfoList());
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			return 1;
		} else if (PayType.BALANCE_PAY.equals(order.getPaytype())) {
			return payService.balanceRefund(workOrder, aid, aName);
		}

		if (ProductType.Normal.getType() == order.getOrderType()) {
			//普通商品退款相关操作
			OrderProduct opP = orderProductMapper.selectByPrimaryKey(workOrder.getOgid());
			//佣金作废
			this.refundCommissionUpdate(order, opP, workOrder);
		}
		return 0;
	}


	@Override
	public int saveWorkOutTimeConfig(WorkConfig config) {
		if (config == null) {
			return 0;
		}
		return workConfigMapper.insertSelective(config);
	}



	@Override
	@Transactional(rollbackFor = Exception.class)
	public int saveWorkOrder(WorkOrder workOrder) {
		if (workOrder == null) {
			logger.info("work order is null");
			return 0;
		}
		if (workOrder.getMid() == null || workOrder.getOgid() == null) {
			logger.info("work order lose tmid or ogid!");
			return 0;
		}
		Long orderId = workOrder.getOid();
		if (orderId == null) {
			logger.info("lose orderId");
			return 0;
		}
		Order order = orderMapper.selectByPrimaryKey(orderId);
		if (order == null) {
			return 0;
		}
		Member tm = memberMapper.selectByPrimaryKey(workOrder.getMid());
		if (tm == null) {
			logger.info("not found tm by id:{}", workOrder.getMid());
			return 0;
		}
		Long ogid = workOrder.getOgid();
		OrderProduct op = orderProductMapper.selectByPrimaryKey(ogid);
		if (workOrder.getNums().intValue() <= 0) {
			throw new BDException("退款数量必须大于0");
		}
		if (workOrder.getNums().intValue() > op.getTotal().intValue()) {
			throw new BDException("退款数量不能大于购买数量");
		}
		//已退数量
		Integer retiredNums = workOrderMapper.getWorkOgNums(ogid);
		if (retiredNums != null && retiredNums + workOrder.getNums() > op.getTotal().intValue()) {
			throw new BDException("订单已退" + retiredNums + "剩余可退数量" + (op.getTotal().intValue() - retiredNums));
		}
//        WorkOrderExample example = new WorkOrderExample();
//        WorkOrderExample.Criteria criteria = example.createCriteria();
//        criteria.andOgidEqualTo(ogid.intValue());
//        List<WorkOrder> workOrderList = workOrderMapper.selectByExample(example);
//        if( workOrderList.size() > 0 ){
//            throw new BDException("已经申请售后，请勿重复提交");
//        }

		workOrder.setUpMid(tm.getUpTeamid());
		workOrder.setUpRealname(tm.getUpTeamname());
		workOrder.setRealname(tm.getRealname());
		workOrder.settXiaoqu(tm.gettXiaoqu());
		workOrder.setOid(orderId);
		workOrder.setCentreId(order.getCentreId());
		workOrder.setOgid(op.getId());
		workOrder.setGoodsid(op.getProductId());
		workOrder.setWorksn(CommonUtils.getSn("WORK"));
		//退款金额
		BigDecimal money = op.getMarketprice().multiply(new BigDecimal(workOrder.getNums()));
		//优惠券 优惠金额
		BigDecimal discountPrice = op.getDiscountPrice();
		if (discountPrice != null) {
			int refundNum = op.getRefundNum();
			if (refundNum == 0) {
				money = money.subtract(discountPrice);
			}
		}

		workOrder.setMoney(money);
		workOrder.setNums(workOrder.getNums());

		WorkClass wc = workClassService.getByKey(workOrder.getType());
		if (wc != null) {
			workOrder.setTypename(wc.getTypename());
			if (wc.getId() == 1) {
				//退全款
				workOrder.setCommissionMoney(op.getCommision1()==null?BigDecimal.ZERO:op.getCommision1().multiply(BigDecimal.valueOf(workOrder.getNums()))
						.divide(BigDecimal.valueOf(op.getTotal()), 2, RoundingMode.HALF_UP));
			}
		}

		if (Objects.equals(PayType.BALANCE_PAY, order.getPaytype())) {
			workOrder.setCredit2money(workOrder.getMoney());
		} else if (PayType.WX_PAY.equals(order.getPaytype()) || PayType.WX_APP_PAY.equals(order.getPaytype())) {
			workOrder.setPaymoney(workOrder.getMoney());
		}
		workOrderMapper.insertSelective(workOrder);

		op.setStatus(OrderStatus.work_access.getCode());
		op.setWorkId(workOrder.getId());
		orderProductMapper.updateByPrimaryKeySelective(op);

		order.setStatus(OrderStatus.work_access.getCode());
		return orderMapper.updateByPrimaryKeySelective(order);
	}


	@Override
	@Transactional(rollbackFor = Exception.class)
	public int cancelWorkOrder(Long workId) {
		if (workId == null) {
			return 0;
		}
		WorkOrder workOrder = workOrderMapper.selectByPrimaryKey(workId);
		if (workOrder == null) {
			logger.info("not found work order by id:{}", workId);
			return 0;
		}
		workOrder.setIsdelete(1);

		Long orderId = workOrder.getOid();
		if (orderId == null) {
			return 0;
		}

		int count = orderProductMapper.countByOrderIdAndStatus(orderId, OrderStatus.work_access.getCode());
		if (count == 1) {
			Order order = new Order();
			order.setId(orderId);
			order.setStatus(OrderStatus.delivery_success.getCode());
			orderMapper.updateByPrimaryKeySelective(order);
		}

		OrderProductExample ope = new OrderProductExample();
		ope.or().andOrderidEqualTo(orderId);
		OrderProduct op = new OrderProduct();
		op.setOrderid(orderId);
		op.setStatus(OrderStatus.delivery_success.getCode());
		orderProductMapper.updateByExampleSelective(op, ope);
		return workOrderMapper.updateByPrimaryKeySelective(workOrder);
	}



}
